﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing.Design;
using System.ComponentModel;
using System.Windows.Forms.Design;
using SharpBolt.Graphics;
using System.Windows.Forms;
using SharpBolt;
using SharpBolt.Graphics.GraphicSources;
using System.IO;

namespace SharpBolt.Editing
{
    class UIImageSourceEditor : UITypeEditor
    {
        public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
        {
            return UITypeEditorEditStyle.Modal;
        }

        public override object EditValue(ITypeDescriptorContext context, System.IServiceProvider provider, object value)
        {
            IWindowsFormsEditorService svc = provider.GetService(typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService;
            if (svc != null)
            {
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.InitialDirectory = Path.GetFullPath(Engine.ResourcesPrefix);
                ofd.Filter = "Image|*.png;*.jpg;*.bmp;*.gif";
                if (ofd.ShowDialog() != DialogResult.OK) return value;
                string shortName = ofd.FileName;

                if (!shortName.Contains(Engine.ResourcesPrefix))
                {
                    var fileName = shortName.Remove(0, shortName.LastIndexOf(@"\") + 1);
                    fileName = fileName.Insert(fileName.LastIndexOf('.'), "_"+Path.GetFileNameWithoutExtension(Path.GetRandomFileName()));
                    var newpath = Path.Combine(Engine.ResourcesPrefix, @"custom\" + fileName);
                    File.Copy(shortName, newpath, true);
                    shortName = newpath;
                }

                shortName = shortName.Remove(0, shortName.LastIndexOf(Engine.ResourcesPrefix) + Engine.ResourcesPrefix.Length);
                ImageSource NewImageSource = ImageSource.LoadImage(shortName);
                return NewImageSource;
            }

            return value;
        }
    }
}
